//
//  Storagable.swift
//  Exam-iOS
//
//  Created by lishengfeng on 2018/3/11.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
///通过NSCoding序列化，将对象存储到本地
protocol Storagable { }
extension Storagable where Self : NSObject {
    
    //获取
    static func fetch() -> Self? {
        guard let path = filePath() else { return nil }
        
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? Self
        
    }
    
    //保存
    @discardableResult //忽略返回值
    func storage() -> Bool {
        
        //序列化
        guard let path = Self.filePath() else { return false }
        //将account转换成二进制数据存到文件
        let result = NSKeyedArchiver.archiveRootObject(self, toFile: path)
        return result
    }
    
    //删除
    func remove() {
        
        guard let path = Self.filePath() else { return }
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: path) {
            do
            {
                try fileManager.removeItem(atPath: path)
            }
            catch let error {
                lsf_alert(error.localizedDescription)
            }
        }
    }
    
    //存储文件路径
    private static func filePath() -> String? {
        
        guard let direct = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first else { return nil }
        
        let type = NSStringFromClass(Self.classForCoder())
        let path = direct + "/" + type + ".txt"
        return path
    }
}
